import { reactive, ref } from 'vue'
import { createRole, deleteRole, deleteRoleByName, fetchRoleDetail, fetchRoleList, updateRole } from '@/services/api'
import { Toast } from '@/utils/uniapi/prompt'

export const useRoleData = () => {
  const loading = ref(false)

  /** 查询对象 */
  const query = reactive<ApiModels.IBaseQueryParams>({
    keyword: '', // 关键词
    page: 1, // 当前页数
    pageSize: 20, // 每页值
  })

  /** 分页列表 */
  const pageList = ref<ApiModels.PageList<ApiModels.base.ApplicationRole>>({
    list: [],
    page: 1,
    totalPageCount: 0,
    totalItemCount: 0,
  })

  /**
   * 获取详情
   * @param id id
   */
  const getDetail = async (id: string) => {
    const res = await fetchRoleDetail(id)
    return res.error ? null : res.data
  }

  /**
   * 获取列表
   * @param page 页码
   * @param pageSize 页面大小
   */
  const getList = async (page?: number, pageSize?: number) => {
    page && (query.page = page)
    pageSize && (query.pageSize = pageSize)
    loading.value = true
    const res = await fetchRoleList({ ...query })
    if (!res.error)
      pageList.value = res.data
    loading.value = false
  }

  /** 修改页数 */
  const changePage = async (page: number) => {
    await getList(page)
  }

  /** 修改分页大小 */
  const changePageSize = async (pageSize: number) => {
    query.pageSize = pageSize
    await getList(1)
  }

  /** 创建 */
  const createHandle = async (data: ApiModels.base.ApplicationRole) => {
    const res = await createRole(data)
    if (res.error) {
      Toast(res.error.msg || '服务端异常')
      return res
    }
    Toast('成功创建')
    await getList(1)
    return res
  }

  /** 更新 */
  const updateHandle = async (data: ApiModels.base.ApplicationRole) => {
    const res = await updateRole(data)
    if (!res.error) {
      Toast('成功更新')
      const index = pageList.value.list.findIndex(i => i.id === data.id)
      index >= 0 && pageList.value.list.splice(index, 1, res.data)
    }
    return res
  }

  /** 删除 */
  const removeHandle = async (id: string) => {
    const res = await deleteRole(id)
    if (res.error) {
      Toast(res.error.msg || '服务端异常')
      return res
    }
    const index = pageList.value.list.findIndex(i => i.id === id)
    index >= 0 && pageList.value.list.splice(index, 1)
    Toast('成功删除')
    return res
  }

  /** 删除 */
  const removeByNameHandle = async (name: string) => {
    const res = await deleteRoleByName(name)
    if (res.error) {
      Toast(res.error.msg || '服务端异常')
      return res
    }
    const index = pageList.value.list.findIndex(i => i.name === name)
    index >= 0 && pageList.value.list.splice(index, 1)
    Toast('成功删除')
    return res
  }

  return {
    loading,
    query,
    pageList,
    getDetail,
    getList,
    changePage,
    changePageSize,
    createHandle,
    updateHandle,
    removeHandle,
    removeByNameHandle,
  }
}
